package cn.szzsi.common.model;

import cn.szzsi.common.model.Product.WeightUnit;
import cn.szzsi.common.model.base.BaseOrders;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 实体类 - 订单
 *
 */

public class Orders extends BaseOrders<Orders> {

	private static final long serialVersionUID = 2186711390821790352L;
	
	public static final Orders dao = new Orders().dao();

	public static final int DEFAULT_ORDER_LIST_PAGE_SIZE = 10;// 订单列表默认每页显示数

	//订单评价(待评价,已评价)
	public enum OrderEvaluate{
		notevaluate,alreadyevaluate
	}

	// 订单状态（未处理、已处理、已完成、已作废）
	public enum OrderStatus {
		unprocessed, processed, completed, invalid
	};

	// 付款状态（未支付、部分支付、已支付、部分退款、全额退款,退款中）
	public enum PaymentStatus {
		unpaid, partPayment, paid, partRefund, refunded,inRefund
	};

	// 配送状态（未发货、部分发货、已发货、部分退货、已退货,退货中）
	public enum ShippingStatus {
		unshipped, partShipped, shipped, partReshiped, reshiped,inReshiped
	};

	
	/**
	 * 根据Member、Pager获取订单分页对象
	 * 
	 * @return 订单分页对象
	 */
	public Page<Orders> getOrderPager (int pageNumber, int pageSize, String memberId) {
		String select = "select * ";
		String sqlExceptSelect = " from mall_orders where member_id = ? order by createDate desc";
		Page<Orders> pager = dao.paginate(pageNumber, pageSize, select, sqlExceptSelect,memberId);
		return pager;
	}
	
	public OrderStatus getOrderStatusValue() {
		return OrderStatus.values()[getInt("orderStatus")];
	}
	public OrderEvaluate getOrderEvaluateValue(){
		return OrderEvaluate.values()[getInt("orderEvaluate")];
	}
	
	public PaymentStatus getPaymentStatusValue() {
		return PaymentStatus.values()[getInt("paymentStatus")];
	}
	
	public ShippingStatus getShippingStatusValue() {
		return ShippingStatus.values()[getInt("shippingStatus")];
	}
	
	public WeightUnit getProductWeightUnitValue(){
		System.out.println(WeightUnit.values()[getInt("productWeightUnit")]);
		return WeightUnit.values()[getInt("productWeightUnit")];
	}
	
	// 获取会员
	public Member getMember(){
		return Member.dao.findById(getStr("member_id"));
	}
		
	// 产品项
	public Product getProduct(){
		return OrderItem.dao.getProduct();
	}
		
	public List<Product> getProductItemList(){
		System.out.println(this);
		return OrderItem.dao.getProductItemList();
		
	}
	
	public PaymentConfig getPaymentConfig() {
		return PaymentConfig.dao.findById(getStr("paymentConfig_id"));
	}

	/**
	 * 配送方式
	 * @return
	 */
	public DeliveryType getDeliveryType() {
		return  DeliveryType.dao.findById(getStr("deliveryType_id"));
	}

	/**
	 * 物流公司
	 * @return
	 */
	public DeliveryCorp getDeliveryCorp() {
		DeliveryType deliveryType=DeliveryType.dao.findById(getStr("deliveryType_id"));
		String defaultDeliveryCorp_id=deliveryType.getDefaultdeliverycorpId();
		return  DeliveryCorp.dao.findById(defaultDeliveryCorp_id);
	}

	public Receiver getReciver(){
		return Receiver.dao.findById(getStr("receiverId"));
	}
	
	/**
	 * 获取未处理订单数
	 *            
	 * @return 未处理订单数
	 */
	public Long getUnprocessedOrderCount() {
		String sql = "select count(*) from mall_orders where orderStatus = ?";
		return Db.queryLong(sql, OrderStatus.valueOf(OrderStatus.unprocessed.name()).ordinal());
	}
	
	/**
	 * 获取已支付未发货订单数（不包含已完成或已作废订单）
	 *            
	 * @return 已支付未发货订单数
	 */
	public Long getPaidUnshippedOrderCount() {
		String sql = "select count(*) from mall_orders  where paymentStatus = ? and shippingStatus = ? and orderStatus != ? and orderStatus != ?";
		return Db.queryLong(sql, PaymentStatus.valueOf(PaymentStatus.paid.name()).ordinal(), ShippingStatus.valueOf(ShippingStatus.unshipped.name()).ordinal(), OrderStatus.valueOf(OrderStatus.completed.name()).ordinal(), OrderStatus.valueOf(OrderStatus.invalid.name()).ordinal());
	}

	public Orders getOrderBySN(String sn){
		String sql = "select * from mall_orders where orderSn = ?";
		return dao.findFirst(sql,sn);
	}
	
	
	/**
	 * 获取最后生成的订单编号
	 * 
	 * @return 订单编号
	 */
	public String getLastOrderSn() {
		String sql = "select orderSn from mall_orders  order by createDate desc";
		Orders order =  dao.findFirst(sql);
		if (order != null) {
			return order.getStr("orderSn");
		} else {
			return null;
		}
	}
	
	// 收款
	public List<Payment> getPaymentList() {
		String sql = "select * from mall_payment t where t.order_id = ? order by createDate desc";
		return Payment.dao.find(sql,getStr("id"));
	}
	
	// 退款
	public List<Refund> getRefundList() {
		String sql = "select * from mall_refund t where t.order_id = ? order by createDate desc";
		return Refund.dao.find(sql,getStr("id"));
	}
	
	// 订单项(目前只查看没有发货的)
	public List<OrderItem> getOrderItemList(String orderId,String userId,String shopId,String type) {
		SiteConfig siteConfig=SiteConfig.dao.findByShopId(shopId);
		if (siteConfig.getProductRank() == 1 && !shopId.equals(userId)) {//开启分管权限
			String sql = "select * from mall_order_item where order_id = ?  and product_id in(select id from mall_product where creator=?) order by createDate desc";
			if("dfh".equals(type)){
				sql = "select * from mall_order_item where order_id = ? and totalDeliveryQuantity ='0'  and product_id in(select id from mall_product where creator=?) order by createDate desc";
			}
			return OrderItem.dao.find(sql,orderId,userId);
		}else{
			String sql = "select * from mall_order_item where order_id =? order by createDate desc";
			return OrderItem.dao.find(sql,orderId);
		}

	}

	// 订单项
	public List<OrderItem> getOrderItemList() {
		String sql = "select * from mall_order_item where order_id = ? order by createDate desc";
		return OrderItem.dao.find(sql,getStr("id"));
	}
	
	// 订单日志
	public List<OrderLog> getOrderLogList() {
		String sql = "select * from mall_order_log where order_id = ? order by createDate desc";
		return OrderLog.dao.find(sql,getStr("id"));
	}
	
	// 发货
	public List<Shipping> getShippingList() {
		String sql = "select * from mall_shipping t where t.order_id = ? order by createDate desc";
		return Shipping.dao.find(sql,getStr("id"));
	}
	
	// 退货
	public List<Reship> getReshipList() {
		String sql = "select * from mall_reship t where t.order_id = ? order by createDate desc";
		return Reship.dao.find(sql,getStr("id"));
	}

	//若该订单已支付,将订单状态改为已支付
	public static void updatePaymentStatus(String orderId){
		Db.update("update mall_orders set paymentStatus='2' where id=?",orderId);

	}

	/**
	 * 根据订单号查询订单
	 * @param trade_no
	 * @return
	 */
	public Orders getOrderByTransactionId(String trade_no){
		return dao.findFirst("select * from mall_orders where trade_no=?",trade_no);
	}
	/**
	 * 根据订单号查询订单
	 * @param paymentConfig_id
	 * @return
	 */
	public Orders getOrderByPaymentConfigId(String paymentConfig_id){
		return dao.findFirst("select * from mall_orders where paymentConfig_id=?",paymentConfig_id);
	}
	/**
	 * 根据OpenId查询订单
	 * @param openId
	 * @return
	 */
	public List<Orders> getOrderByOpenId(String openId){
		return dao.find("select * from mall_orders where openId=?",openId);
	}

	public UserBalance getUserBalance(){
		return UserBalance.dao.findByMemberId(getStr("member_id"));
	}

	/**
	 * 批量审核订单
	 */
	public void batchcheck(String[] ids) {
		if (ids != null) {
			StringBuilder sb = new StringBuilder("");
			for (String id : ids) {
				sb.append(id).append("\',\'");
			}
			String idstr = sb.toString();
			if (StringUtils.isNotBlank(idstr) && idstr.endsWith("\',\'")) {
				idstr = idstr.substring(0, idstr.lastIndexOf("\',\'"));
			}
			Db.update("update mall_orders set checks=1 where id in (\'" + idstr + "\')");
		}
	}

	/**
	 * 查询用户是否已经购买过商品
	 * @param member
	 * @return
	 */
	public Orders isAlreadyBuy(Member member){
		return dao.findFirst("select * from mall_orders o where o.paymentStatus=2 and o.checks = 0");
	}

	public void initParams(){
		List<OrderItem> orderItemList=getOrderItemList();
		String specificationvaluesAll="";
		for(OrderItem orderItem:orderItemList){
			String specificationvalues="";
			String productName=orderItem.getProductName();
			Integer productQuantuantity=orderItem.getProductQuantity();
			String specificationValuesName= orderItem.getSpecificationvaluesAll();
			specificationvalues="商品:"+productName+"&nbsp;规格:"+specificationValuesName+"&nbsp;数量:"+productQuantuantity;
			specificationvaluesAll+=specificationvalues+"</br>";
		}
		this.put("orderDetail","<p>"+specificationvaluesAll+"<p>");
		//规格名称
		/*String vs = this.getStr("specificationvalues");
		if(StrKit.notBlank(vs)){
			List<Record> lists = Db.find("select name from mall_specification_value where id in ('"+StringUtils.replace(StringUtils.removeEnd(vs,","),",","','")+"')");
			String valuenames = "";
			if(lists != null && lists.size()>0){
				for(Record r:lists){
					valuenames += r.getStr("name")+" ";
				}
				this.put("valuenames",valuenames);
			}
		}*/
	}

	public BigDecimal getUnpaidAmount(){
		if (getPaymentStatus() == 0){
			return getTotalAmount().subtract(getPaidDeposit()).subtract(getPaidPointAsDeposit());
		}
		return new BigDecimal(0);
	}


	/**
	 * 父级订单号
	 * @param parentId
	 * @return
	 */
	public List<Orders> getByParentId(String parentId){
		return dao.find("select * from mall_orders o where o.parentId=?",parentId);
	}
}
